// server.ts
import { CompleteMultipartUploadCommand, CreateMultipartUploadCommand, ListPartsCommand, S3Client, UploadPartCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import cors from 'cors';
import dotenv from 'dotenv';
import express from 'express';
dotenv.config();

const app = express();
app.use(cors());
app.use(express.json());

const s3 = new S3Client({
  logger: console, // 直接输出日志到控制台
  clientLogMode: 'debug', // 详细日志模式
  region: process.env.AWS_REGION,
  endpoint: process.env.AWS_S3_ENDPOINT,
  forcePathStyle: true,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  },
});


// 初始化分块上传
app.post('/api/initiate-upload', async (req, res) => {
  try {
    const { fileName, fileType } = req.body;
    const command = new CreateMultipartUploadCommand({
      Bucket: process.env.S3_BUCKET_NAME,
      Key: fileName,
      ContentType: fileType,
    });
    const response = await s3.send(command);
    res.json({ uploadId: response.UploadId });
  } catch (error) {
    res.status(500).json({ error: '初始化上传失败' });
  }
});

// 获取分块预签名URL
app.post('/api/get-presigned-url', async (req, res) => {
  try {
    const { fileName, uploadId, partNumber } = req.body;
    const command = new UploadPartCommand({
      Bucket: process.env.S3_BUCKET_NAME,
      Key: fileName,
      UploadId: uploadId,
      PartNumber: partNumber,
    });
    const url = await getSignedUrl(s3, command, { expiresIn: 3600 });
    res.json({ presignedUrl: url });
  } catch (error) {
    res.status(500).json({ error: '获取签名URL失败' });
  }
});

// 查询已上传分块
app.post('/api/list-parts', async (req, res) => {
  try {
    const { fileName, uploadId } = req.body;
    const command = new ListPartsCommand({
      Bucket: process.env.S3_BUCKET_NAME,
      Key: fileName,
      UploadId: uploadId,
    });
    const response = await s3.send(command);
    res.json({ parts: response.Parts || [] });
  } catch (error) {
    res.status(500).json({ error: '查询分块失败' });
  }
});

// 完成上传
app.post('/api/complete-upload', async (req, res) => {
  try {
    const { fileName, uploadId, parts } = req.body;
    const command = new CompleteMultipartUploadCommand({
      Bucket: process.env.S3_BUCKET_NAME,
      Key: fileName,
      UploadId: uploadId,
      MultipartUpload: { Parts: parts },
    });
    const response = await s3.send(command);
    res.json({ location: response.Location });
  } catch (error) {
    res.status(500).json({ error: '完成上传失败' });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));